const { list, userList } = require('./mock')
const bodyParser = require('body-parser')
module.exports = app => {
	app.use(bodyParser.json())
	// 存储验证码
	let systemCode = Math.random().toString().slice(2, 6)

	app.get('/api/list', (req, res) => {
		const { pageCode = 1, pageSize = 10, value = '' } = req.query;
		if (value) {
			const filterList = list.filter(v => {
				return Object.values(v).some(item => item.toString().includes(value))
			})
			res.send({
				code: 200,
				data: filterList
			})
		} else {
			res.send({
				code: 200,
				data: list.slice((pageCode - 1) * pageSize, pageCode * pageSize)
			})
		}
	})

	app.get('/api/code', (req, res) => {
		const { tel } = req.query;

		const item = userList.find(v => tel === v.tel)
		if (item) {
			// 生成验证码
			systemCode = Math.random().toString().slice(2, 6)
			// 返回验证码
			res.send({
				code: 200,
				message: '验证码获取成功',
				data: {
					systemCode,
				}
			})
		} else {
			res.send({
				code: 401,
				message: '该手机号未注册.'
			})
		}
	})

	app.post('/api/tel/signin', (req, res) => {
		const { tel, code } = req.body;

		const item = userList.find(v => tel === v.tel && code === systemCode)

		if (item) {
			// 返回验证码
			res.send({
				code: 200,
				message: '登录成功',
				data: {
					nickname: item.nickname,
					tags: item.tags,
					tel: item.tel
				}
			})
		} else {
			res.send({
				code: 401,
				message: '验证码错误或者手机号不存在'
			})
		}
	})
}